import json
import os
import uuid
from django.conf import settings
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from card_app.public_func import CardCounter, AudioRecognizer

# Create your views here.

class VoiceSearchView(View):
    def post(self, request):
        audio_file = request.FILES.get('file')  # 从请求中获取文件
        if not audio_file:
            return JsonResponse({"error": "没有上传音频文件。"}, status=400)
        if not audio_file.name.lower().endswith('.wav'):
            return JsonResponse({"error": "文件格式不正确，请上传 .wav 格式的文件。"}, status=400)
        new_filename = f"{uuid.uuid4()}.wav"
        save_dir = os.path.join(settings.MEDIA_ROOT, settings.VOICE_DIR)
        os.makedirs(save_dir, exist_ok=True)
        save_path = os.path.join(save_dir, new_filename)
        with open(save_path, 'wb+') as destination:
            for chunk in audio_file.chunks():
                destination.write(chunk)
        recognizer = AudioRecognizer()
        recognizer.db_build_templates()
        cards, best_score = recognizer.recognize_with_vad(save_path)
        print(cards, best_score)
        recognizer.delete_audio_file(save_path)
        cards_list = cards.split(",")
        deck = request.session.get('deck')
        if deck:
            counter = CardCounter(deck=deck)
        else:
            counter = CardCounter()
            request.session['deck'] = counter.deck

        play_result = counter.play_cards(cards_list)
        # 保存更新后的牌堆
        request.session['deck'] = counter.deck

        return JsonResponse({
            "message": cards,
            "play_result": play_result,
            "deck": counter.show_deck()
        }, status=200)

class VoiceProcessingView(View):
    def post(self, request):
        audio_file = request.FILES.get('file')  # 从请求中获取文件
        content = request.POST.get("content")
        if not audio_file:
            return JsonResponse({"error": "没有上传音频文件。"}, status=400)
        if not audio_file.name.lower().endswith('.wav'):
            return JsonResponse({"error": "文件格式不正确，请上传 .wav 格式的文件。"}, status=400)
        new_filename = f"{uuid.uuid4()}.wav"
        save_dir = os.path.join(settings.MEDIA_ROOT, settings.VOICE_DIR)
        os.makedirs(save_dir, exist_ok=True)
        save_path = os.path.join(save_dir, new_filename)
        with open(save_path, 'wb+') as destination:
            for chunk in audio_file.chunks():
                destination.write(chunk)

        recognizer = AudioRecognizer()
        recognizer.build_templates(save_path, content)
        return JsonResponse({
            "message": "文件已成功保存。",
            "filename": new_filename,
            "filepath": os.path.join('test', new_filename)  # 相对MEDIA_URL的路径
        }, status=200)

    def get(self, request):
        return render(request, 'card/voice_processing.html')


class CardCounterPageView(View):
    def get(self, request):

        return render(request, 'card/card_counter.html')


class ResetDeckView(View):
    def post(self, request):
        counter = CardCounter()
        new_deck = counter.reset_deck()
        # 保存到 Session
        request.session['deck'] = counter.deck
        return JsonResponse({
            "message": "牌堆已重置。",
            "deck": counter.show_deck()
        }, status=200)


class ShowDeckView(View):
    def get(self, request):
        deck = request.session.get('deck')
        if deck:
            counter = CardCounter(deck=deck)
        else:
            counter = CardCounter()
            request.session['deck'] = counter.deck
        return JsonResponse({
            "deck": counter.show_deck()
        }, status=200)


class PlayCardsView(View):
    def post(self, request):
        try:
            data = json.loads(request.body)
            cards = data.get('cards', [])
            if not isinstance(cards, list):
                return JsonResponse({"error": "'cards' 应该是一个列表。"}, status=400)
        except json.JSONDecodeError:
            return JsonResponse({"error": "无效的JSON格式。"}, status=400)

        deck = request.session.get('deck')
        if deck:
            counter = CardCounter(deck=deck)
        else:
            counter = CardCounter()
            request.session['deck'] = counter.deck

        play_result = counter.play_cards(cards)
        # 保存更新后的牌堆
        request.session['deck'] = counter.deck

        return JsonResponse({
            "play_result": play_result,
            "deck": counter.show_deck()
        }, status=200)
